using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace Windows_Explorer.Class
{
    class clsItem
    {
        clsTreeView cls = new clsTreeView();
        private static string sourceDir = "", dest = "", sourceFile = "";
        public string strSrceFile
        {
            set
            {
                sourceFile = value;
            }
            get
            {
                return sourceFile;
            }
        }
        public string strSrceDir
        {
            set 
            {
                sourceDir = value;
            }
            get
            {
                return sourceDir;
            }
        }
        public string strDestDir
        {
            set
            {
                dest = value;
            }
            get
            {
                return dest;
            }
        }
        /* Ham copy file va folder
        public bool CopyDirectory(string strSrceDir, string strDestDir)
        {
            try
            {
                string[] arrSrceDir = strSrceDir.Split('\\');
                string folder = arrSrceDir[arrSrceDir.Length - 1];
                string strDest = strDestDir + folder;
                DirectoryInfo SourceDir = new DirectoryInfo(strSrceDir);
                DirectoryInfo DestDir = new DirectoryInfo(strDest);
                if (!DestDir.Exists)
                    DestDir.Create();
                foreach (FileInfo ChildFile in SourceDir.GetFiles())
                {
                    ChildFile.CopyTo(Path.Combine(DestDir.FullName, ChildFile.Name), true);
                }
                foreach (DirectoryInfo SubDir in SourceDir.GetDirectories())
                {
                    if (!SubDir.Exists)
                        SubDir.Create();
                    bool retVal;
                    retVal = CopyDirectory(SubDir.FullName, Path.Combine(DestDir.FullName, SubDir.Name));
                    if (!retVal)
                        return false;
                }
                return true;
            }
            catch 
            {
                //log any error...
                throw;
            }
        }
        public void CopyFile(string strSrceFile, string strDestDir)
        {
            FileInfo sourceFile = new FileInfo(strSrceFile);
            DirectoryInfo destDir = new DirectoryInfo(strDestDir);
            FileInfo isexist = new FileInfo(Path.Combine(destDir.FullName, sourceFile.Name));
            if (!destDir.Exists)
                destDir.Create();
            if (isexist.Exists)
            {
                DialogResult d = MessageBox.Show("Tên file này đã tồn tại!\n Bạn có muốn copy đè lên nó không?", "Confirm File Replace", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (d == DialogResult.Yes) sourceFile.CopyTo(Path.Combine(destDir.FullName, sourceFile.Name), true);
            }
            else sourceFile.CopyTo(Path.Combine(destDir.FullName, sourceFile.Name), true);
        }
         */

        /// <summary>
        /// Delete item with Dialog to confirm
        /// </summary>
        /// <param name="item"></param>
        /// <param name="listView"></param>
        public void DeleteItem(ListViewItem item, ListView listView)
        {
            try
            {
                string path = item.SubItems[4].Text;
                if (item.SubItems[1].Text == "File Folder")
                {
                    DirectoryInfo dir = new DirectoryInfo(path);
                    if (!dir.Exists)
                    {
                        cls.ShowErrorPath();
                        return;
                    }
                    else
                    {
                        
                        DialogResult d = MessageBox.Show("Are you sure want to remove the folder '" 
                            + item.Text.ToString() + "' and all its\ncontents?",
                            "Confirm Folder Delete", MessageBoxButtons.YesNo,
                            MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                        if (d == DialogResult.Yes)
                        {
                            DeleteReadOnlyFile(dir);
                            Contains(dir);
                            if (fileCount == 0)
                            {
                                folderCount = 0;
                                if (dir.Attributes.ToString().Contains("ReadOnly"))
                                    dir.Attributes ^= FileAttributes.ReadOnly;
                                dir.Delete(true);
                            }
                            else
                            {
                                folderCount = 0;
                                fileCount = 0;
                                /////return;
                            }
                            try
                            {
                                CheckFolder(dir);
                                CheckFolder(dir);
                                CheckFolder(dir);
                                CheckFolder(dir);
                                CheckFolder(dir);
                                CheckFolder(dir);
                            }
                            catch { }
                        }
                        else return;
                    }
                    
                }
                else
                {
                    FileInfo file = new FileInfo(path);
                    if (!file.Exists)
                    {
                        cls.ShowErrorPath();
                        return;
                    }
                    else
                    {
                        if (file.Attributes.ToString().Contains("ReadOnly"))
                        {
                            DialogResult d1 = MessageBox.Show("The file '" + file.Name + 
                                "' is a read-only file. Are you sure \nwant to delete it?",
                                "Confirm File Delete", MessageBoxButtons.YesNo,MessageBoxIcon.Question, 
                                MessageBoxDefaultButton.Button1);
                            if (d1 == DialogResult.Yes)
                            {
                                file.Attributes ^= FileAttributes.ReadOnly;
                                file.Delete();
                            }
                            else return;
                        }
                        else
                        {
                            DialogResult dd = MessageBox.Show("Are you sure want to delete '" + 
                                item.Text.ToString() + "'?", "Confirm File Delete", MessageBoxButtons.YesNo, 
                                MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                            if (dd == DialogResult.Yes)
                            {
                                file.Delete();
                            }
                            else return;
                        }
                    }
                    
                }
                if (path == Microsoft.VisualBasic.FileIO.SpecialDirectories.Desktop + 
                    "\\" + item.SubItems[0].Text.Trim().ToString() + "\\" ||
                    path == Microsoft.VisualBasic.FileIO.SpecialDirectories.Desktop + 
                    "\\" + item.SubItems[0].Text.Trim().ToString())
                {
                    Program.fmain.tvTreeView.Nodes[0].Remove();
                    clsTreeView.CreateTreeView(Program.fmain.tvTreeView);
                    cls.GetDesktop(Program.fmain.tvTreeView.Nodes[0], Program.fmain.lvListView);
                }
                else
                    cls.OpenFolder(cls.Path, listView);

            }
            catch (Exception ex)
            {
                clsTreeView.ShowError(ex);
            }
        }
        
        /// <summary>
        /// Delete file without warning for user.
        /// </summary>
        /// <param name="item"></param>
        /// <param name="listView"></param>
        public void DeleteItems(ListViewItem item, ListView listView)
        {
            try
            {
                string path = item.SubItems[4].Text;
                if (item.SubItems[1].Text == "File Folder")
                {
                    DirectoryInfo dir = new DirectoryInfo(path);
                    if (!dir.Exists)
                    {
                        cls.ShowErrorPath();
                        return;
                    }
                    else
                    {
                        //dir.Delete(true);
                        DeleteReadOnlyFile(dir);
                        Contains(dir);
                        if (fileCount == 0)
                        {
                            folderCount = 0;
                            if (dir.Attributes.ToString().Contains("ReadOnly")) 
                                dir.Attributes ^= FileAttributes.ReadOnly;
                            dir.Delete(true);
                        }
                        else
                        {
                            folderCount = 0;
                            fileCount = 0;
                            /////return;
                        }
                        try
                        {
                            CheckFolder(dir);
                            CheckFolder(dir);
                            CheckFolder(dir);
                            CheckFolder(dir);
                            CheckFolder(dir);
                            CheckFolder(dir);
                        }
                        catch { }
                    }
                }
                else
                {
                    FileInfo file = new FileInfo(path);
                    if (!file.Exists)
                    {
                        cls.ShowErrorPath();
                        return;
                    }
                    else
                    {
                        if (file.Attributes.ToString().Contains("ReadOnly"))
                        {
                            DialogResult d1 = MessageBox.Show("The file '" + file.Name +
                                "' is a read-only file. Are you sure \nwant to delete it?",
                                "Confirm File Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                MessageBoxDefaultButton.Button1);
                            if (d1 == DialogResult.Yes)
                            {
                                file.Attributes ^= FileAttributes.ReadOnly;
                                file.Delete();
                            }
                            else return;
                        }
                        else
                            file.Delete();
                    }
                }
                
            }
            catch (Exception ex)
            {
                clsTreeView.ShowError(ex);
            }
        }

        /// <summary>
        /// Delete directory could contains file(s) read-only
        /// </summary>
        /// <param name="dir"></param>
        private void DeleteReadOnlyFile(DirectoryInfo dir)
        {
            
            foreach (FileInfo fi in dir.GetFiles())
            {
                if (fi.Attributes.ToString().Contains("ReadOnly"))
                {
                    DialogResult d = MessageBox.Show("The file '" + fi.Name +
                                "' is a read-only file. Are you sure \nwant to delete it?",
                                "Confirm File Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                MessageBoxDefaultButton.Button1);
                    if (d == DialogResult.Yes)
                    {
                        fi.Attributes ^= FileAttributes.ReadOnly;
                        fi.Delete();
                    }
                }
                else
                {
                    fi.Delete();
                }
            }
            foreach (DirectoryInfo subDir in dir.GetDirectories())
            {
                if (subDir.Attributes.ToString().Contains("ReadOnly")) subDir.Attributes ^= FileAttributes.ReadOnly;
                DeleteReadOnlyFile(subDir);
            }
        }

        /// <summary>
        /// Check if the directory empty, let's delete it.
        /// And recursion it again for all sub-directory
        /// </summary>
        /// <param name="dir"></param>
        private void CheckFolder(DirectoryInfo dir)
        {
            if (dir.GetFiles().Length == 0 && dir.GetDirectories().Length == 0)
            {
                dir.Delete();
                return;
            }
            else
            {
                foreach (DirectoryInfo subDir in dir.GetDirectories())
                {
                    CheckFolder(subDir);
                }
            }
        }

        /// <summary>
        /// Move the item to the specific destination.
        /// </summary>
        /// <param name="pathMove"></param>
        /// <param name="item"></param>
        /// <param name="listView"></param>
        public void MoveItem(string pathMove, ListViewItem item, ListView listView)
        {
            try
            {
                string path = item.SubItems[4].Text;
                if (item.SubItems[1].Text == "File Folder")
                {
                    DirectoryInfo dir = new DirectoryInfo(path);
                    if (!dir.Exists)
                    {
                        cls.ShowErrorPath();
                        return;
                    }
                    dir.MoveTo(pathMove);
                }
                else
                {
                    FileInfo file = new FileInfo(path);
                    if (!file.Exists)
                    {
                        cls.ShowErrorPath();
                        return;
                    }
                    file.MoveTo(pathMove);
                }
                cls.OpenFolder(cls.Path, listView);
            }
            catch (Exception ex)
            {
                clsTreeView.ShowError(ex);
            }
        }

        public static int folderCount = 0, fileCount = 0;
        public static long folderSize = 0;
        /// <summary>
        /// List all of file and folders in a directory.
        /// </summary>
        /// <param name="dir"></param>
        public static void Contains(DirectoryInfo dir)
        {
            foreach (FileInfo fi in dir.GetFiles())
            {
                fileCount++;
                folderSize += fi.Length;
            } 
            foreach (DirectoryInfo di in dir.GetDirectories())
            {
                folderCount++;
                Contains(di);
            }
        }
    }
}
